﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualBasic.FileIO;

namespace WebService.Proxy
{
    public class UsgsServiceProxy : IEarthquakeServiceProxy
    {
        const string url = "http://earthquake.usgs.gov/earthquakes/catalogs/eqs7day-M2.5.txt";

		// NOTE: Replacing this implementation with a CsvFile.Parse based version
		// would be a cool "stay green" refactoring demo.
        public async Task<IEnumerable<EarthquakeEvent>> GetDataAsync()
        {
            var client = new HttpClient();
            var stream = await client.GetStreamAsync(url);

            var parser = new TextFieldParser(stream);
            parser.TextFieldType = FieldType.Delimited;
            parser.SetDelimiters(",");
            parser.HasFieldsEnclosedInQuotes = true;

            var dti = new DateTimeFormatInfo();
            dti.LongDatePattern = "dddd, MMMM d, HH:mm:ss K";

            var result = new List<EarthquakeEvent>();
            var fields = parser.ReadFields(); // first line contains field names... ignore it
            while (!parser.EndOfData)
            {
                fields = parser.ReadFields();

                result.Add(new EarthquakeEvent
                {
                    Latitude = Decimal.Parse(fields[4]),
                    Longitude = Decimal.Parse(fields[5]),
                    Magnitude = Decimal.Parse(fields[6]),
                    Title = fields[9],
                    Datetime = DateTime.Parse(fields[3].Replace("UTC", "+0"), dti),
                });
            }

            return result;
        }
    }
}
